<?php

namespace core\library;

use core\utils\Bean;

/**
 * 记录访问日志
 * Class Log
 * @package core\library
 */
class Log implements Bean
{
    private static $instance = null;

    private static $logDir;


    public static function getInstance(string $logDir = 'logs') {
        if (null === self::$instance) {
            self::$logDir = $logDir;
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct() {
        if (!file_exists(self::$logDir)) {
            if (is_writable('.'))
                mkdir(self::$logDir, 0744);
            else
                throw new \Error('unable to create dir `' . self::$logDir . '`');
        }
        if (is_dir(self::$logDir)) {
            if (!is_writable(self::$logDir)) {
                throw new \Error('log dir `' . self::$logDir . '` not write able');
            }
        }
    }

    public function log($handle) {
        $format = [
            'REMOTE_ADDR' => $_SERVER['HTTP_REFERER'] ?? null,                            // 访问的客户端
            'TIME_LOCAL' => date('Y-m-d H:i:s'),                                  // 访问的时间
            'REQUEST' => Input::getInstance()->get('s'),                                  // 访问的url地址
            'HTTP_REFERER' => $_SERVER['HTTP_REFERER'] ?? null,                           // 来源页面
            'STATUS' => http_response_code(),                                             // 页面的返回码
            'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? null,                     // 用户的浏览器版本
            'GET' => $_GET,                                                               // GET 参数
            'POST' => $_POST,                                                             // POST 参数
            'METHOD' => $_SERVER['REQUEST_METHOD'] ?? null,                               // 请求的方法
            'REQUEST_TIME' => $_SERVER['REQUEST_TIME'],                                   // 请求的时间
            'TIME_USE' => microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],  // 处理请求用时
            'http_x_forward_for'
        ];
        fprintf($handle, "%s\n", json_encode($format, JSON_UNESCAPED_UNICODE));
    }
    public function access() {
        // 在构造器里面已经检验过这个的文件权限了， 这里不再重复检验， 下同
        $handle = fopen(self::$logDir . '/access.log', 'a+');
        $this->log($handle);
    }
    public function error() {
        $handle = fopen(self::$logDir . '/error.log', 'a+');
        $this->log($handle);
    }
}